<template>
	<view class="container">
		<button class="scan-btn" type="primary">
			总共： {{sumCount}}
		</button>
		<button v-show="status === '0'" class="scan-btn" type="primary" @click="onSubmit">
			<uni-icons type="submit" size="18" color="#fff"></uni-icons>
			提交
		</button>
		<!-- <button v-show="status === '0'" class="scan-btn" type="primary" @click="scanCode">
      <uni-icons type="scan" size="18" color="#fff"></uni-icons>
      开始扫描
    </button> -->

		<!-- #ifdef APP-PLUS -->
		<xw-scan></xw-scan>
		<!-- #endif -->

		<view class="table-container">
			<view class="table-header">
				<view class="table-cell header-cell">条码</view>
				<view class="table-cell header-cell">扫码时间</view>
				<view class="table-cell header-cell">添加人</view>
				<view class="table-cell header-cell">数量</view>
				<view class="table-cell header-cell">操作</view>
			</view>

			<view class="table-body">
				<view class="table-row" v-for="(item, index) in input" :key="index" @longpress="editDtl(item)">
					<view class="table-cell code-cell">{{item.code}}</view>
					<view class="table-cell time-cell">{{item.time}}</view>
					<view class="table-cell time-cell">{{item.name}}</view>
					<view class="table-cell time-cell">{{item.qty}}</view>
					<view class="table-cell time-cell" @click="deleteCode(item)">删除</view>
				</view>

				<view v-if="input.length === 0" class="empty-tip">
					<image src="/static/empty.png" mode="aspectFit"></image>
					<text>暂无扫描数据</text>
				</view>
			</view>
		</view>
		<view v-if="showInput" class="custom-modal">
			<view class="modal-mask" @click="showInput = false"></view>
			<view class="modal-content">
				<view class="modal-header">请输入数量</view>
				<view class="modal-body">
					<input type="number" v-model="inputValue" placeholder="请输入大于0的整数" @input="handleInput"
						class="number-input" />
				</view>
				<view class="modal-footer">
					<button @click="handleConfirmClose">取消</button>
					<button @click="handleConfirm" :disabled="!isValid">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDuryDtlList,
		scanDury,
		deleteDury,
		endDury,
		editDury
	} from '../../config/api/api.js';
	import moment from 'moment';
	import {
		login
	} from '../../config/comm.js';

	function formatDate(date) {
		return moment(date).format('YYYY-MM-DD HH:mm:ss');
	}

	export default {
		data() {
			return {
				input: [],
				audio: uni.createInnerAudioContext(),
				current: 1,
				page: 1,
				total: 0,
				dtlId: '',
				status: 0,
				showInput: false,
				inputValue: 1,
				code: '',
				goodsQty: 0,
				editFlag: false
			}
		},
		computed: {
			sumCount() {
				return this.input.reduce((sum, {
					qty
				}) => sum + Number(qty), 0);
			},
			except_arr() {
				return this.input.map(el => el.code);
			},
			isValid() {
				const num = parseInt(this.inputValue)
				return !isNaN(num) && num > 0
			},
			onlyCodeQty() {
			  const codeMap = new Map(); // 存储 code前缀 => 最后一个qty
			  
			  this.input.forEach(el => {
			    if (el.code?.length >= 7) {
			      const codePrefix = el.code.slice(0, 7); // 取前7位作为 key
			      codeMap.set(codePrefix, el.qty ?? 1); // 直接覆盖（保留最后一个）
			    }
			  });
			  
			  return codeMap; // 返回 Map { code前缀 => 最后一个qty }
			}
		},
		onLoad(query) {
			this.audio.src = '/static/25.mp3';
			this.audio.volume = 1;
			this.dtlId = query.dtlId;
			this.status = query.status;
			this.goodsQty = query.sum;
			console.log('this.goodsQty', this.goodsQty)
			this.fetch();
		},
		onShow() {
			// #ifdef APP-PLUS
			uni.$off('xwscan')
			uni.$on('xwscan', (res) => {
				this.handleWxScanResult(res.code);
			})
			// #endif
		},
		onUnload() {
			// #ifdef APP-PLUS
			uni.$off('xwscan')
			// #endif
		},
		methods: {
			handleInput(e) {
				this.inputValue = e.detail.value.replace(/[^0-9]/g, '')
				if (!this.inputValue) {
					this.inputValue = '1'
				}
			},
			handleConfirmClose() {
				this.showInput = false
				this.$on('wxscan')
			},
			async handleConfirm() {
				if (this.isValid) {
					await this.scanImmidately();
				}
			},
			editDtl(item) {
				this.code = item.code;
				this.inputValue = item.qty
				this.$off('wxscan')
				this.editFlag = true;
				this.showInput = true;
			},
			async scanImmidately() {
				try {
					// 终止扫码
					this.showInput = false
					// TODO: 新增和编辑判断
					if (this.editFlag) {
						console.log('待对接')
						await editDury({
							drug_code: this.code,
							lsdtlid: this.dtlId,
							qty: this.inputValue
						});
					} else {
						await scanDury({
							drug_code: this.code,
							lsdtlid: this.dtlId,
							qty: this.inputValue
						});
					}
					uni.showToast({
						title: `${this.editFlag ? '添加' : '编辑'}成功`,
						icon: 'success'
					});
					this.audio.play();
				
					// APP端振动
					// #ifdef APP-PLUS
					plus.device.vibrate(1000);
					// #endif
				
					this.fetch();
				} catch (e) {
					uni.showToast({
						title: e,
						icon: 'fail'
					})
				} finally {
					this.$on('wxscan')
				}
			},
			async fetch() {
				uni.showLoading({
					title: '加载中...'
				});
				try {
					const {
						data: {
							data,
							total
						}
					} = await getDuryDtlList({
						page: this.current,
						lsdtlid: this.dtlId
					});
					this.inputValue = '1';
					if (data) {
						this.input = data.map(el => ({
							code: el.drugcode,
							time: el.drug_time,
							name: el.employeename,
							qty: el.qty
						}));
					}
				} finally {
					uni.hideLoading();
				}
			},
			async handleScanResult(result) {
				if (!/^8\d{19}$/.test(result)) {
					return uni.showToast({
						title: '条码格式不正确',
						icon: 'none'
					});
				}
				this.code = result
				this.editFlag = false;
				console.log('code', this.onlyCodeQty.keys())
				if (this.onlyCodeQty.has(result.slice(0,7))) {
					this.inputValue = this.onlyCodeQty.get(result.slice(0,7));
					this.scanImmidately();
				} else {
					this.$off('wxscan')
					this.inputValue = 1
					this.showInput = true
				}
			},
			async handleWxScanResult(result) {
				try {
					if (this.except_arr.includes(result)) {
						return uni.showToast({
							title: '扫码重复',
							icon: 'none'
						});
					}
					await this.handleScanResult(result);
				} catch (e) {
					uni.showToast({
						title: `${e}`,
						icon: 'none'
					});
					alert(`${e}`)
				}
			},
			async deleteCode(record) {

				if (this.status === '0') {
					try {
						await deleteDury({
							"lsdtlid": this.dtlId,
							"drug_code": record.code
						});
						uni.showToast({
							title: `删除成功!`,
							icon: 'success'
						});
						this.fetch();
					} catch (e) {
						console.log(e);
						uni.showToast({
							title: `删除失败!${e}`,
							icon: 'fail'
						})
						throw e;
					}
				} else {
					uni.showToast({
						title: '失败',
						icon: 'error'
					});
				}
			},
			onSubmit() {
			    if (Number(this.goodsQty) !== this.sumCount) {
			        uni.showModal({
			            title: '提示',
			            content: '检测到扫描量与总数不符，是否要继续提交？',
			            confirmText: '确定',
			            cancelText: '取消',
			            success: (res) => {
			                if (res.confirm) {
			                    uni.showModal({
			                        title: '提示',
			                        content: '确定要执行此操作吗？（提交之后不能新增扫码）',
			                        confirmText: '确定',
			                        cancelText: '取消',
			                        success: (res) => {
			                            if (res.confirm) {
			                                try {
			                                    endDury({
			                                        lsdtlid: this.dtlId
			                                    });
			                                    uni.navigateTo({
			                                        url: '/pages/lostModule/lostModule'
			                                    });
			                                } catch (e) {
			                                    uni.showToast({
			                                        title: '提交失败',
			                                        icon: 'error'
			                                    });
			                                }
			                            } else if (res.cancel) {
			                                console.log('用户点击了取消');
			                                return;
			                            }
			                        }
			                    });
			                }
			            }
			        });
			    } else {
			        uni.showModal({
			            title: '提示',
			            content: '确定要执行此操作吗？（提交之后不能新增扫码）',
			            confirmText: '确定',
			            cancelText: '取消',
			            success: (res) => {
			                if (res.confirm) {
			                    try {
			                        endDury({
			                            lsdtlid: this.dtlId
			                        });
			                        uni.navigateTo({
			                            url: '/pages/lostModule/lostModule'
			                        });
			                    } catch (e) {
			                        uni.showToast({
			                            title: '提交失败',
			                            icon: 'error'
			                        });
			                    }
			                } else if (res.cancel) {
			                    console.log('用户点击了取消');
			                }
			            }
			        });
			    }
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		height: 100vh;
		background: #f5f7fa;
	}

	.scan-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 80rpx;
		margin-bottom: 20rpx;
		background: #67c23a;
		color: #fff;
		border-radius: 8rpx;
		font-size: 30rpx;

		.uni-icons {
			margin-right: 10rpx;
		}
	}

	.table-container {
		background: #fff;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.table-header {
		display: flex;
		background: #409eff;
		border-radius: 12rpx 12rpx 0 0;
	}

	.table-body {
		max-height: calc(100vh - 200rpx);
		overflow-y: auto;
	}

	.table-row {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		transition: background 0.3s;

		&:active {
			background: #f5f7fa;
		}
	}

	.table-cell {
		flex: 1;
		padding: 0 20rpx;
		font-size: 28rpx;
		text-align: center;
		word-break: break-all;
		display: flex;
		align-items: center;
		/* 确保单元格内容垂直居中 */
		justify-content: center;
		/* 水平居中 */

		&.header-cell {
			color: #fff;
			font-weight: 500;
			padding: 20rpx;
		}

		&.code-cell {
			color: #333;
			font-weight: 500;
		}

		&.time-cell {
			color: #666;
		}
	}

	.empty-tip {
		padding: 60rpx 0;
		text-align: center;

		image {
			width: 200rpx;
			height: 200rpx;
			opacity: 0.5;
		}

		text {
			display: block;
			margin-top: 20rpx;
			color: #999;
		}
	}

	.custom-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 999;
	}

	.modal-mask {
		position: absolute;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
	}

	.modal-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		background: #fff;
		border-radius: 10px;
		overflow: hidden;
	}

	.modal-header {
		padding: 15px;
		font-size: 16px;
		font-weight: bold;
		text-align: center;
		border-bottom: 1px solid #eee;
	}

	.modal-body {
		padding: 20px;
	}

	.number-input {
		border: 1px solid #ddd;
		padding: 10px;
		border-radius: 4px;
	}

	.modal-footer {
		display: flex;
		border-top: 1px solid #eee;
	}

	.modal-footer button {
		flex: 1;
		margin: 0;
		border-radius: 0;
		border: none;
		background: none;
		line-height: 44px;
	}

	.modal-footer button:last-child {
		color: #007aff;
	}

	.modal-footer button[disabled] {
		color: #ccc;
	}
</style>